package com.jbm.jbmsupplier.presenters;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.jbm.core.common.MainServer;
import com.jbm.core.iface.IAcross;
import com.jbm.jbmsupplier.activity.LoginActivity;
import com.jbm.jbmsupplier.activity.rxjavanet.ModeRxjavaNet;
import com.jbm.jbmsupplier.modes.NewHomeInterface;
import com.jbm.jbmsupplier.net.NetIntent;
import com.jbm.jbmsupplier.net.busheven.UtlisNetWork;
import com.jbm.jbmsupplier.shared.SharedPreferActivity;
import com.jbm.jbmsupplier.utlis.ExitActivity;
import com.jbm.jbmsupplier.utlis.PtesonalPrivile;
import com.jbm.jbmsupplier.view.DialoagButtonLoading;
import com.jbm.jbmsupplier.view.DoubleButtonDialog;
import com.jbm.jbmsupplier.views.NewHomeView;
import com.jbm.jbmsupplier.zp.service.MyService;
import com.jbm.onehome.common.OHInterface;
import com.jbm.onehome.iface.PrivilegeListEntity;

import java.util.ArrayList;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * Created by 家帮忙 on 2017/7/7.
 */

public class NewHomeActivitys implements NewHomeInterface{
    private Context context;
    private NewHomeView newHomeView;

    private SharedPreferActivity sharedPreferActivity;
    private int modework;
    private MyNetWorkBroadCast network;
    private MyConnSock mycon=null;
    private IntentFilter filer;
    private final int LOGINNEW=0002;
    private final int EXITPWD=0005;
    public NewHomeActivitys(Context context, NewHomeView newHomeView) {
        this.context = context;
        this.newHomeView = newHomeView;
    }

    @Override
    public void setInitMode() {//初始化
        sharedPreferActivity=new SharedPreferActivity(context,true);
        network = new MyNetWorkBroadCast();//监听网络
        if (network!=null){
        context.registerReceiver(network, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));}
        if (sharedPreferActivity.getBoolearNetConn()==false){
            mycon=new MyConnSock();
            filer= new IntentFilter();
            filer .addAction("SOCKCONN");
            context.registerReceiver(mycon,filer) ;
        }

    }
    @Override
    public void setnewLogin() {//有网络

     Thread thread=new Thread(runnable);
        thread.start();
        newHomeView.getTextUser().setText(sharedPreferActivity.getNmaes().substring(0,sharedPreferActivity.getNmaes().indexOf(",")));
        if (sharedPreferActivity.getUserNmaes().equals("")){
            newHomeView.getTextUserName().setText(  ModeRxjavaNet.Companion.getInstantMode().getOhInter().nickname);
        }else{
            newHomeView.getTextUserName().setText(sharedPreferActivity.getUserNmaes());
        }
    }

    @Override
    public void SetExitLogin() {
        final DoubleButtonDialog dialog = new DoubleButtonDialog(context,"是否退出当前用户");
        dialog.setNoText("取消");
        dialog.setTetle_message("");
        dialog.setisVisibilitymess();
        dialog.getokbtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//确定
                boolean is =context.deleteFile("userPrson.txt");
                new SharedPreferActivity(context).setExitLogin();
                 context.stopService(new Intent( context,MyService.class));
                context. startActivity(new Intent(context, LoginActivity.class));

                if (mycon!=null){
                    context. unregisterReceiver(mycon);
                }
                if (network!=null){
                    context.unregisterReceiver(network);
                }
                Observable.create(new Observable.OnSubscribe<IAcross>() {
                    @Override
                    public void call(Subscriber<? super IAcross> subscriber) {
                        IAcross exit = ModeRxjavaNet.Companion.getInstantMode().getOhInter().Logout();
                        subscriber.onNext(exit);
                    }
                }).subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(action);
                ExitActivity.getInstance().exitActivity();
                dialog.dismiss();
            }
        });
        dialog.getnobtn().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                dialog.dismiss();
            }
        });

    }

    @Override
    public void setDialogUserName() {//修改用户名
        final DialoagButtonLoading dialog = new DialoagButtonLoading(context);
        dialog.getTitlename().setText("修改昵称");
        dialog.shows();
        dialog.froButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {//确定
                dialog.Loadingshow("加载中...",true);
                ModeRxjavaNet.Companion.getInstantMode().objects(Observable.create(new Observable.OnSubscribe<IAcross>() {
                    @Override
                    public void call(Subscriber<? super IAcross> subscriber) {
                        subscriber.onNext(ModeRxjavaNet.Companion.getInstantMode().getOhInter().ModPerInof(sharedPreferActivity.getLoginid(),  dialog.getEditname().getText().toString(), 0));
                    }
                })).subscribe(new Observer<IAcross>() {
                    @Override
                    public void onCompleted() {

                    }
                    @Override
                    public void onError(Throwable e) {

                    }
                    @Override
                    public void onNext(IAcross iacross) {
                        if (iacross.m_code==200){
                            sharedPreferActivity.setUserName(dialog.getEditname().getText().toString());
                            newHomeView.getTextUserName().setText(dialog.getEditname().getText().toString());
                            dialog.disims();
                        }else {
                            dialog.disims();
                            dialog.hint(iacross.m_info);
                        }


                    }
                });

                dialog.disimm();
            }
        });
        dialog.toButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.disimm();
            }
        });

    }

    Action1<IAcross> action =new Action1<IAcross>(){

        @Override
        public void call(IAcross iAcross) {
            if (iAcross.m_code==200){
                Log.e("main","退出成功");
            }
        }
    };
    Runnable runnable=new Runnable() {
    @Override
    public void run() {
        String allnamepwd= sharedPreferActivity.getNmaes();
        if (!allnamepwd.equals("")){
            NetIntent netintent=new NetIntent(handler);
            netintent.setLogin(allnamepwd.substring(0,allnamepwd.indexOf(",")),allnamepwd.substring(allnamepwd.indexOf(",")+1,allnamepwd.length()),LOGINNEW);
        }
    }
};

    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case LOGINNEW:
                    String login=(String) msg.obj;
                    if (login.equals("Login OK")){
                        sharedPreferActivity.setBoolearNetConn(true);
                        MainServer.getG_server().setM_local_id(sharedPreferActivity.getLoginid());
                        ModeRxjavaNet.Companion.getInstantMode().objects(Observable.create(new Observable.OnSubscribe<PrivilegeListEntity>() {
                            @Override
                            public void call(Subscriber<? super PrivilegeListEntity> subscriber) {
                                subscriber.onNext(ModeRxjavaNet.Companion.getInstantMode().getOhInter().getPersonalPrivilegeList(true,0, OHInterface.getG_server().login_id));
                            }
                        })).subscribe(new Observer<PrivilegeListEntity>() {
                            @Override
                            public void onCompleted() {

                            }
                            @Override
                            public void onError(Throwable e) {

                            }
                            @Override
                            public void onNext(PrivilegeListEntity privilegeListEntity) {
                                if (privilegeListEntity.m_code==200){
                                    ArrayList<PrivilegeListEntity> arrPteson=new ArrayList<PrivilegeListEntity>();
                                    if (privilegeListEntity.priList!=null) {
                                        arrPteson.addAll(privilegeListEntity.priList);
                                        new PtesonalPrivile().setArrPteson(arrPteson, context);//将所有的权限保存在本地
                                        newHomeView.getLoadTitle();
                                    }else{
                                        newHomeView.getLoadTitle();
                                    }

                                }else {
                                    newHomeView.getLoadTitle();
                                }

                            }
                        });
                    }else if (login.equals("FAILED")){
                        //   hint("请求网络超时");
                    }else if (login.equals("request timeout")){
                        Toast.makeText(context, "request timeout", Toast.LENGTH_SHORT).show();
                    }else if (login.equals("Not Connect")){
                        Toast.makeText(context, "Not Connect", Toast.LENGTH_SHORT).show();
                    } else {
                        newHomeView.getExit(login+"请退出后确认密码",handler,EXITPWD,1);
                    }
                    break;
                case EXITPWD:
                    ExitActivity.getInstance().exitActivity();
                    sharedPreferActivity.setExitLogins();
                    break;


            }
            super.handleMessage(msg);
        }
    };

    class MyConnSock extends BroadcastReceiver {//在联网成功时调用
        @Override
        public void onReceive(Context context, Intent intent)
        {if (intent.getStringExtra("comm").equals("1")){
//            setnewLogin() ;  //有网络登录
            Log.e("main","成功");
        }else if (intent.getStringExtra("comm").equals("3")){
//            setnewLogin() ;  //有网络登录
            Log.e("main","成功");
        }
        }
    }

    private boolean IsConn;
    class MyNetWorkBroadCast extends BroadcastReceiver {//监听网络的变化
        @Override
        public void onReceive(final Context context, Intent intent) {
            if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)){
                modework = UtlisNetWork.getnetwokstate(context);
                if (modework == 0||modework == 1) {
                    IsConn=true;
                    if (sharedPreferActivity.getBoolearLogin() == true) {
                        if (IsConn==true){
                            if (sharedPreferActivity.getBoolearNetConn()==true){
                                setnewLogin(); //有网络登录
                                IsConn=false;
                            }else{
                                context.startService(new Intent(context, MyService.class));
                                IsConn=false;
                            }
                        }
                    }
                    return;
                } else if (modework == -1) {
                    if (IsConn==false){
                                Toast.makeText(context,  "未连接网络，请联网后在进入", Toast.LENGTH_SHORT).show();
                        sharedPreferActivity.setBoolearNetConn(false);
                                IsConn=true;
                    }
                    return;
                }
            }
        }

    }
    public void SetonBackPressed(){//点击back
        if (network!=null){
            context.unregisterReceiver(network);
        }
        if (mycon!=null){
           context. unregisterReceiver(mycon);
        }
    }


}
